package com.fifth.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fifth.common.pojo.dto.CommonResult;
import com.fifth.common.pojo.entity.UserInfo;
import com.fifth.common.pojo.entity.UserPermission;
import com.fifth.user.feign.BusinessFeign;
import com.fifth.user.feign.SsoFeign;
import com.fifth.user.mapper.UserMapper;
import com.fifth.user.mapper.UserPermissionMapper;
import com.fifth.user.service.UserService;
import com.fifth.user.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @作者：刘壬杉
 * @创建时间 2022/8/31 11:29
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SsoFeign ssoFeign;
    @Autowired
    private BusinessFeign businessFeign;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserPermissionMapper userPermissionMapper;

    /**
     * 根据tel查询用户信息
     * @param telephone
     * @return
     */
    @Override
    public UserInfo findByPhone(String telephone) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("telephone",telephone);
        return userMapper.selectOne(queryWrapper);
    }
    //注册
    @Override
    public CommonResult signInsert(String telephone,String password) {

        String s = UUID.randomUUID().toString();
        String salt = s.substring(0,3);

        String o =  ssoFeign.signInsert(password,salt);
        //System.out.println(o+"==============");
        UserInfo userInfo = new UserInfo();
        userInfo.setTelephone(telephone);
        userInfo.setPassword(o);
        userInfo.setSalt(salt);
        int insert = userMapper.insert(userInfo);
        if (insert!=0){
            return new CommonResult(2000,"注册成功",null);
        }
        return new CommonResult(5000,"注册失败",null);

    }
    //用户登录修改个人信息
    @Override
    public CommonResult updateMessage(UserInfo userInfo) {
        HttpServletRequest request = WebUtils.getRequest();
        //获取token请求头
        String token = request.getHeader("token");
        //获取登陆者信息
        Map map=JSON.parseObject(redisTemplate.opsForValue().get(token),Map.class);
            Map user = (Map) map.get("user");
            userInfo.setId((String) user.get("id"));
            int i = userMapper.updateById(userInfo);
            return new CommonResult(2000, "修改成功", null);

    }
    //用户修改密码
    @Override
    public CommonResult updatePassword(String telephone,String password) {
        HttpServletRequest request = WebUtils.getRequest();
        //获取token请求头
        String token = request.getHeader("token");
        //获取登陆者信息
        Map map=JSON.parseObject(redisTemplate.opsForValue().get(token),Map.class);
        //拿到redis里面的缓存内容
        Map user = (Map) map.get("user");
        String salt = (String) user.get("salt");
        String id = (String) user.get("id");
        String tele = (String) user.get("telephone");
        //判断用户手机号是否与登录信息相同
        if (telephone.equals(tele)){
            //openfeign远程调用加密
                //远程调用加密存入数据库
                String s = ssoFeign.signInsert(password, salt);
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setPassword(s);
            int i = userMapper.updateById(userInfo);
            return new CommonResult(2000,"修改成功,请重新登录",null);
        }
        return new CommonResult(5000,"该手机号错误",null);
    }

    @Override
    public CommonResult findUserById() {
        //获取token
        HttpServletRequest request = WebUtils.getRequest();
        //获取token请求头
        String token = request.getHeader("token");
        //获取登陆者信息
        Map map=JSON.parseObject(redisTemplate.opsForValue().get(token),Map.class);
        if (map!=null && map.containsKey("user")) {
            Map user = (Map) map.get("user");
            String id = (String) user.get("id");
            UserInfo userInfo = userMapper.selectById(id);
            return new CommonResult(2000, "查询成功", userInfo);
        }
        return new CommonResult(4000,"用户未登录",null);
    }
    //查询所有权限
    @Override
    public List<UserPermission> getPermission() {
        QueryWrapper<UserPermission> queryWrapper = new QueryWrapper<>();
        return userPermissionMapper.selectList(queryWrapper);
    }

    @Override
    public CommonResult updateByid(String id,Integer status) {
        HttpServletRequest request = WebUtils.getRequest();
        String token = request.getHeader("token");
        Map map = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        Map user = (Map) map.get("user");
        String ename = (String) user.get("ename");
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        UserInfo userInfo = new UserInfo();
        userInfo.setStatus(status);
        userInfo.setUpdateman(ename);
        userMapper.update(userInfo,queryWrapper);
        return new CommonResult(2000,"操作成功",null);
    }

    @Override
    public CommonResult getUserAll(Integer currentPage, Integer pageSize,String startTime,String endTime) {
        IPage<UserInfo> page = new Page<>(currentPage,pageSize);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(startTime)){
            queryWrapper.ge("createtime",startTime);
        }
        if (StringUtils.hasText(endTime)){
            queryWrapper.le("createtime",endTime);
        }
        IPage<UserInfo> userAll = userMapper.getUserAll(page, queryWrapper);
        System.out.println("总页码:" + page.getPages());
        System.out.println("总条数:" + page.getTotal());
        System.out.println("当前页记录:" + page.getRecords());
        return new CommonResult(2000,"查询成功",userAll);
    }

    @Override
    public CommonResult numberUser() {
        Map map= userMapper.numberUser();
        map.put("name","用户");
        Map numbershop = businessFeign.numbershop();
        numbershop.put("name","商家");

        List<Map> list=new ArrayList<>();
        list.add(map);
        list.add(numbershop);


        return new CommonResult(2000,"查询成功",list);
    }

    @Override
    public CommonResult businessTotal() {
        List<Map> list = businessFeign.numberBusiness();
        return new CommonResult(2000,"查询成功",list);
    }

    @Override
    public CommonResult priceBusiness() {
        List<Map> list = businessFeign.priceBusiness();
        List<String> name = new ArrayList<>();
        List<Double> value = new ArrayList<>();
        for (Map m:list) {
            name.add((String) m.get("name"));
            value.add((Double) m.get("value"));
        }
        List arrayList = new ArrayList();
        arrayList.add(name);
        arrayList.add(value);
        return new CommonResult(2000,"查询成功",arrayList);
    }
}
